package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Created: with IntelliJ IDEA.
 * @author:
 * @createTime: 2020-06-29 19:44
 **/

@Controller
public class HelloController {

    @Value("${sso.server.url}")
    String ssoServerUrl;


    /**
     * 无需登录就可访问
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/hello")
    public String hello() {
        return "hello";
    }

/**
 * 感知有没有登入成功
 *
 * **/

    @GetMapping(value = "/employees")
    public String employees(Model model, HttpSession session, @RequestParam(value = "token",required = false) String token) {
       //判断token是否为空
       if (!StringUtils.isEmpty(token)){
           //去sso登入成功后返回会带上token
           //1.TODO 去sso获取当前token的真正值的用户信息
           RestTemplate restTemplate = new RestTemplate();
           // 发送GET请求获取 reids中的数据
           ResponseEntity<String> forEntity = restTemplate.getForEntity("http://sso.com:8080/userInfo?token=" + token, String.class);
           //获取请求体   也就是值
           String body = forEntity.getBody();
           //将值放在session中
           session.setAttribute("loginUser",body);
       }
        List<String> emps = new ArrayList<>();
     //获取session的值
        Object loginUser = session.getAttribute("loginUser");
     //判断   获取的值是不是空
        if (loginUser == null) {
            //没登录,跳转到服务器登录
        return "redirect:"+ssoServerUrl+"?redirect_url=http://client1.com:8081/employees";
        } else {
            emps.add("张三");
            emps.add("李四");
        }
        model.addAttribute("emps",emps);
        return "employees";
    }

}
